﻿using AfrikDotnetWebSite.Models;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace AfrikDotnetWebSite.Controllers
{
    public class AboutController : Controller
    {
        AfrikDotnetContext db = new AfrikDotnetContext();

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        public ActionResult Index()
        {
            var siteSettings = db.SiteSettings;
            ViewBag.Email = siteSettings.Where(s => s.Key.ToLower() == "email").Select(s => s.Value).FirstOrDefault();
            ViewBag.Logo = siteSettings.Where(s => s.Key.ToLower() == "logo").Select(s => s.Value).FirstOrDefault();
            ViewBag.WebSite = siteSettings.Where(s => s.Key.ToLower() == "website").Select(s => s.Value).FirstOrDefault();

            ViewBag.UserGroups = db.UserGroups;

            var donations = db.Donations.ToList();
            ViewBag.Donations = donations;
            var years = donations.Select(d => d.Year).Distinct().OrderByDescending(d => d);
            ViewBag.Years = years;
            ViewBag.LastDonations = donations.Where(d => d.Year == years.First()).ToList();

            return View();
        }

        public JsonResult GetDonations(int year)
        {
            var donations = db.Donations.Where(d => d.Year == year).ToList();
            StringBuilder sb = new StringBuilder();

            foreach (var donation in donations)
            {
                if (donations.IndexOf(donation) == 0)
                {
                    sb.Append(donation.Donor + " (" + donation.Description + ")");
                }
                else
                {
                    sb.Append(" - " + donation.Donor + " (" + donation.Description + ")");
                }
            }

            return Json(sb.ToString(), JsonRequestBehavior.AllowGet);
        }
    }
}
